// 第一步 打开数据（和数据库建立连接）
const dbRequest = indexedDB.open("xjh");
dbRequest.onerror = function (err) {
  console.log("打开数据库失败~~");
};

let db = null;
dbRequest.onsuccess = function (event) {
  db = event.target.result;
};

// 第一次打开、 或者版本发生跟新
dbRequest.onupgradeneeded = function (event) {
  const db = event.target.result;
  // 创建一些存储对象， 主键为 id
  db.createObjectStore("users", { keyPath: "id" });
};

class User {
  constructor(id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
  }
}

const users = [
  new User(100, "why", 19),
  new User(101, "why2", 19),
  new User(102, "why4", 192),
];

let btns = document.querySelectorAll(".button");
for (let i = 0; i < btns.length; i++) {
  btns[i].onclick = function () {
    // 创建事项
    const transaction = db.transaction("users", "readwrite");

    // 获取到 数据表
    const store = transaction.objectStore("users");

    switch (i) {
      case 0:
        console.log("点击新增");
        for (const user of users) {
          // 数据表添加
          const request = store.add(user);
          request.onerror = function () {
            console.log("error ~~");
          };
        }
        break;
      case 1:
        console.log("点击查询");
        // 数据表获取
        const request = store.get(102);
        // 这个每次都是的返回结果就是这样的额一个监听。。
        request.onsuccess = function (e) {
          console.log(e.target.result);
        };
        break;
      case 2:
        console.log("点击删除");
        const deleteRequest = store.openCursor();
        deleteRequest.onsuccess = (e) => {
          const cursor = e.target.result;
          if (cursor) {
            if (cursor.key == 102) {
              cursor.delete();
            } else {
              cursor.continue();
            }
          }
        };
        break;

      case 3:
        console.log("点击修改");
        const updateRequest = store.openCursor();
        updateRequest.onsuccess = (e) => {
          const cursor = e.target.result;
          if (cursor) {
            if (cursor.key == 101) {
              const value = cursor.value;
              value.age = 3030;
              cursor.update(value);
            } else {
              cursor.continue();
            }
          }
        };
        break;
    }
  };
}
